<?php

$sqlFiles = array('core','users','grants','pages');

session_start();

$dbName = '';
$createDB = false;
$host = '127.0.0.1';
$user = '';
$site = '';
$smarty_path = dirname(dirname(dirname(__FILE__))).'/smarty/';

if (!empty($_POST))
{
	$params = file_get_contents(dirname(__FILE__)."/config.php.tpl");
	$params = str_replace('{$HOST}',$_POST['host'],$params);
	$params = str_replace('{$DB}',$_POST['dbname'],$params);
	$params = str_replace('{$USER}',$_POST['user'],$params);
	$params = str_replace('{$PASS}',$_POST['pass'],$params);
	$params = str_replace('{$PATH}',dirname(dirname(__FILE__)).'/',$params);
	$params = str_replace('{$ROOT_PATH}',$_SERVER['DOCUMENT_ROOT'].'/',$params);
	$params = str_replace('{$SITE}',$_POST['site'],$params);
	$params = str_replace('{$SMARTY}',$_POST['smarty_path'],$params);
	file_put_contents(dirname(__FILE__).'/../config.php',$params);
	
	$dbName = $_SESSION['cf_install_db'] = $_POST['dbname'];
	$createDB = $_SESSION['cf_install_create_db'] = array_key_exists('createDB',$_POST);
	$host = $_SESSION['cf_install_host'] = $_POST['host'];
	$user = $_SESSION['cf_install_user'] = $_POST['user'];
	$site = $_SESSION['cf_install_site'] = $_POST['site'];
	$smarty_path = $_SESSION['cf_install_smarty_path'] = $_POST['smarty_path'];

	if ($createDB) {
		require_once dirname(__FILE__).'/../config.php';
		require_once dirname(__FILE__).'/../db_pdo.php';
		$db = new cf\Database('mysql:host='.cf\Config::host, cf\Config::user, cf\Config::pass, 'utf8');
		$q = new cf\Query($db);
		$q->exec("
			DROP DATABASE IF EXISTS $dbName;
			CREATE DATABASE $dbName DEFAULT CHARACTER SET utf8;
			USE $dbName;
		");
	}
	
	require_once dirname(__FILE__).'/../db.php';
	require_once dirname(__FILE__).'/../user.php';	
	
	if (array_key_exists('modules',$_POST)) {
		foreach ($_POST['modules'] as $module) {
			$sqlFiles[] = $module;
		}
	}
	foreach ($sqlFiles as $f) {
		$sql = 'SET storage_engine=MYISAM;' . file_get_contents(dirname(__FILE__)."/$f.sql");
		cf\execQuery($sql);
	}

	cf\User::register('admin','admin','Admin');
	cf\execQuery("
		INSERT INTO cf_roles (id,name) VALUES('admin','Администраторы');
		INSERT INTO cf_user_roles (role_id,user_id) VALUES('admin',1);
		INSERT INTO cf_role_view_grants   (view_id,   role_id, can_read)    VALUES (NULL,'admin',1);
		INSERT INTO cf_role_action_grants (action_id, role_id, can_execute) VALUES (NULL,'admin',1);
	");
} else {
	if (array_key_exists('cf_install_db',$_SESSION)) {
		$dbName = $_SESSION['cf_install_db'];
	}
	if (array_key_exists('cf_install_create_db',$_SESSION)) {
		$createDB = (bool)$_SESSION['cf_install_create_db'];
	}
	if (array_key_exists('cf_install_host',$_SESSION)) {
		$host = $_SESSION['cf_install_host'];
	}
	if (array_key_exists('cf_install_user',$_SESSION)) {
		$user = $_SESSION['cf_install_user'];
	}
	if (array_key_exists('cf_install_smarty_site',$_SESSION)) {
		$smarty_path = $_SESSION['cf_install_smarty_site'];
	}
	if (array_key_exists('cf_install_smarty_path',$_SESSION)) {
		$smarty_path = $_SESSION['cf_install_smarty_path'];
	}
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
      <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title>Инсталляция</title>
</head>	
<body>

<div style="width:500px; margin:0px auto; border:1px solid #DDD; background-color:#F2F5F7; padding:20px;">
<form method=post>
<table>
	<tr>
		<td>
			Имя MySQL базы данных: 
		</td>
		<td>
			<input type=text name='dbname' value='<?php echo $dbName; ?>'>
		</td>
	</tr>
	<tr>
		<td>
			Создать БД (DROP... CREATE DATABASE ...): 
		</td>
		<td>
			<input type=checkbox name='createDB'>
		</td>
	</tr>
	<tr>
		<td>
			Имя хоста MySQL:
		</td>
		<td>
			<input type=text name='host' value='<?php echo $host; ?>'>
		</td>
	</tr>
	<tr>
		<td>
			Имя пользователя MySQL:
		</td>
		<td>
			<input type=text name='user' value='<?php echo $user; ?>'>
		</td>
	</tr>
	<tr>
		<td>
			Пароль MySQL:
		</td>
		<td>
			<input type=text name='pass' value=''>
		</td>
	</tr>
	<tr>
		<td>
			Имя сайта:
		</td>
		<td>
			<input type=text name='site' value='<?php echo $site; ?>'>
		</td>
	</tr>
	<tr>
		<td>
			Путь к Smarty:
		</td>
		<td>
			<input type=text name='smarty_path' value='<?php echo $smarty_path; ?>'>
		</td>
	</tr>
	<tr>
		<td>
			Модули:
		</td>
		<td>
			<input type=checkbox name='modules[]' value='news' checked>Новости <br>
			<input type=checkbox name='modules[]' value='gallery' checked>Галерея <br>
			<input type=checkbox name='modules[]' value='shop' checked>Торговый каталог <br>
			<input type=checkbox name='modules[]' value='shop_orders' checked>Магазин <br>
			<input type=checkbox name='modules[]' value='shop_market' checked>Маркет <br>
		</td>
	</tr>
	<?php if (get_magic_quotes_gpc()) {?>
	<tr>
		<td colspan=2 style="border:1px solid #CD0A0A; color:#CD0A0A;">
			<p style="text-align:center;"><strong>Внимание!</strong></p>
			Magic Quotes должны быть отключены. Это может быть сделано одним из следующих способов:
			<ul>
				<li>Добавьте <strong>magic_quotes_gpc = Off</strong> в файл php.ini</li>
				<li>Добавьте <strong>php_flag magic_quotes_gpc Off</strong> в файл .htaccess в корневой дирестории вашего сайта.
			</ul>
		</td>
	</tr>
	<?php } ?>
	<tr>
		<td colspan=2 style="text-align:right;">
			<button type=submit style="padding:10px;">OK</button>
		</td>
	</tr>
</table>
</form>
</div>
</body>
</html>